<template>
    <div>
        <div class="top">
            <div class="title">{{title}}</div>
            <div class="change-tip" v-if="hasChecked">
                (标
                <span class="color-block"></span>色字段为正在变更中...)
            </div>
            <div class="float-right">
                <el-button
                    type="primary"
                    @click="checkAndSubmit"
                    v-if="showBtn&&hasEditCol"
                >{{$t("message.submit")}}</el-button>
            </div>
        </div>
        <hr />
        <div v-for="(form,index) in myForms" :key="index">
            <div class="form-title">{{form.title}}</div>
          <!--111-->
          <div class="info">
                <div class="edit-icon">
                    <i
                        class="el-icon-edit-outline"
                        v-if="showBtn&&hasEditCol&&!form.isEdit"
                        @click="editForm(form)"
                    ></i>
                    <i
                        class="el-icon-delete"
                        v-if="showBtn&&hasEditCol&&!form.isEdit&&isDelete"
                        @click="deleteForm(form)"
                    ></i>
                </div>
                <el-form
                    label-position="right"
                    label-width="130px"
                    label-suffix=":"
                    :ref="form.formName"
                    :model="dynamicValidateForms"
                >
                    <div
                        v-for="(item,itemIndex) in form.rows"
                        :key="'item'+itemIndex"
                        :style="itemIndex != form.rows.length-1 ? {'border-bottom':'1px solid #ced6df','margin':'10px 0 15px 0'}:null"
                    >
                        <el-row
                            v-for="(row, rowIndex) in getRows(dynamicValidateForms[form.formName].columns,item.columns)"
                            :key="rowIndex"
                        >
                            <el-col
                                v-for="(col, colIndex) in row"
                                :key="colIndex"
                                :span="col.type=='textarea' || col.type=='file' ? 24 : 8"
                                :class="col.type=='textarea' ? null : 'ie-hack'"
                            >
                                <el-form-item
                                    :prop="form.formName+'.columns.'+col.index+'.columnValue'"
                                    :rules="getAllRules(col,form.formName)"
                                >
                                    <span slot="label">  <!--所有左选项-->
                                        <span
                                            v-if="col.nameZH && col.nameZH.length<=6"
                                            :class="col.inReview?'field-checked':null"
                                        >{{col.nameZH}}：</span>
                                        <el-tooltip
                                            v-else
                                            class="item"
                                            effect="light"
                                            :content="col.nameZH"
                                            placement="top-start"
                                        >
                                            <span
                                                style="cursor:pointer"
                                                :class="col.inReview?'field-checked':null"
                                            >{{col.nameZH.substr(0,6)}}...：</span>
                                        </el-tooltip>
                                    </span>
                                    <template v-if="!form.isEdit||!col.isEdit"> <!--展示-->
                                        <span
                                            v-if="col.type=='date'"
                                            :class="col.inReview?'field-checked':null"
                                        >{{toDateByLong(col.columnValue)}}</span>
                                        
                                        <span
                                            v-else-if="col.type=='select'"
                                            style="word-break:break-all"
                                            :class="col.inReview?'field-checked':null"
                                        >{{getOptionText(col)}}</span>
                                        <template v-else-if="col.type=='image'&&col.columnValue">
                                            <div
                                                class="float-left"
                                                style="min-height:150px"
                                                v-viewer="toolOptions"
                                            >
                                                <img
                                                    :src="getImg(file,form)"
                                                    v-for="(file,imgIndex) in col.columnValue.split(';')"
                                                    :key="imgIndex"
                                                    width="220px"
                                                    height="147px"
                                                    class="file-image"
                                                />
                                            </div>
                                        </template>
                                        <span
                                            v-else
                                            style="word-break:break-all"
                                            :class="col.inReview?'field-checked':null"
                                        >{{col.columnValue}}</span>
                                    </template>
                                    <template v-if="form.isEdit&&col.isEdit"> <!--编辑-->
                                        <el-input
                                            v-if="col.fieldId == 67"
                                            v-model="col.columnValue"
                                            style="width:100%"
                                            disabled
                                        ></el-input>
                                        <!-- 招生专业不允许修改 -->
                                        <el-input
                                            v-if="col.type=='input'"
                                            v-model="col.columnValue"
                                            style="width:100%"
                                            :maxlength="col.length"
                                        ></el-input>
                                        <el-select
                                            v-if="col.type=='select'&&col.fieldId !== 67&&col.value!=null&&col.value!='G_XZQY'&& getOptions(form,col.value) && getOptions(form,col.value).length<=6"
                                            v-model="col.columnValue"
                                            style="width:100%"
                                            :filterable="col.isSearch"
                                            @change="ralationField.includes(col.column)?handleRalationField(form,col):null"
                                            clearable
                                        >
                                            <el-option
                                                v-for="item in getOptions(form,col.value)"
                                                :key="item.value"
                                                :label="item.label"
                                                :value="item.value"
                                            />
                                        </el-select>
                                        <el-select
                                            v-if="col.fieldId=='166'"
                                            v-model="col.columnValue"
                                            style="width:100%"
                                            :filterable="col.isSearch"
                                            @change="ralationField.includes(col.column)?handleRalationField(form,col):null"
                                            clearable
                                        >
                                            <el-option
                                                v-for="item in universList"
                                                :key="item.value"
                                                :label="item.label"
                                                :value="item.value"
                                            />
                                        </el-select>
                                        <pager-select
                                            v-if="col.type=='select'&&col.fieldId !== 67&&col.value!=null&&col.value!='G_XZQY'&& getOptions(form,col.value) && getOptions(form,col.value).length>6"
                                            :data="getOptions(form,col.value)"
                                            @input="changexx(form,col)"
                                            v-model="col.columnValue"
                                        />
                                        <!-- <pager-select
                                            v-if="col.type=='select'&&col.value === null&&col.fieldId == 68"
                                            :data="options.XJZY"
                                            v-model="col.columnValue"
                                        /> -->
                                        <!-- 学籍专业下拉框 -->
                                        <el-select
                                            v-if="col.type=='select'&&col.value === null&&col.fieldId == 68"
                                            v-model="col.columnValue"
                                            style="width:100%"
                                            :filterable="col.isSearch"
                                        >
                                            <el-option
                                                v-for="item in options.XJZY"
                                                :key="item.value"
                                                :label="item.label"
                                                :value="item.value"
                                            />
                                        </el-select>
                                        <select-tree
                                            v-if="col.type=='select'&&col.value=='G_XZQY'"
                                            :data="citys"
                                            v-model="col.columnValue"
                                        />
                                        <el-input
                                            type="textarea"
                                            v-if="col.type=='textarea'"
                                            :rows="5"
                                            v-model="col.columnValue"
                                        ></el-input>
                                        <el-date-picker
                                            v-if="col.type=='date'"
                                            v-model="col.columnValue"
                                            type="date"
                                            format="yyyy-MM-dd"
                                            value-format="yyyy-MM-dd"
                                            placeholder="选择日期"
                                            style="width:100%"
                                        ></el-date-picker>
                                        <el-upload
                                            v-if="col.type=='image'"
                                            action="/api/commonservice/obsfile/uploadfile"
                                            :data="{bucketname: 'face', folderpath: 'file'}"
                                            list-type="picture-card"
                                            :before-upload="beforeAvatarUpload"
                                            :on-remove="function(a,b){handleRemove(a,b,form)}"
                                            :on-error="handleError"
                                            :on-exceed="handleExceed"
                                            :on-success="function(a,b,c){handleSuccess(a,b,c,form)}"
                                            :limit="2"
                                            :file-list="form.files"
                                            class="file-upload"
                                        >
                                            <i class="el-icon-plus"></i>
                                        </el-upload>
                                        <el-date-picker
                                            v-if="col.type=='year'"
                                            v-model="col.columnValue"
                                            type="year"
                                            value-format="yyyy"
                                            placeholder="选择年"
                                            @input="gradeChange"
                                        ></el-date-picker>
                                    </template>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </div>
                </el-form>
                <div class="float-right" v-if="form.isEdit">
                    <el-button @click="cancel(form)">{{$t("message.cancel")}}</el-button>
                    <el-button type="primary" @click="save(form)">{{$t("message.confirm")}}</el-button>
                </div>
            </div>
        </div>
        <div class="add-btn" v-if="showBtn&&isMulti" @click="addForm">
            <span>+</span>
            <span>新增{{title}}</span>
        </div>
        <difference-dialog
            ref="diffDialog"
            :post-data="postData.stuDetailInfoList"
            :raw-data="data"
            :options="options"
            :checked="checked"
            @save-diff="hasCheckSubmit"
            @update="init"
            :city="[]"
            :label="title"
            :isMulti="isMulti"
        ></difference-dialog>
    </div>
</template>
<script>
import {
    getStudentDetail,
    stuDetailSubmit,
    findStuDicLinkage,
    getDirections,
    findStatusProfessionList
} from "common/src/api/studentinfo";
import { queryDic, queryZYFX } from "common/src/api/dictionary";
import UTILS from "common/src/utils/utils";
import differenceDialog from "./differenceDialog";
import { submitField, getRules, getCitys } from "./businessMethods";
import { getImageData, universities, getCollegeListByNationCode } from "common/src/api/teacherinfo";
import moment from "moment";
const ADD_FORM = "0";
const FORM_TYPE = {
    ADD: 1,
    EDIT: 2,
    DELETE: 3
};
export default {
    name: "statusInfo",
    props: ["uid", "tableName", "title", "isDelete", "isMulti", "showBtn"],
    data() {
        return {
            myForms: [],
            tempVal: '',
            dynamicValidateForms: {},
            XY: '',
            DQNJ: '',
            XJXY: '', // 学籍学院
            XWLX: '',
            data: [],
            postData: {
                studentId: this.uid,
                stuDetailInfoList: []
            },
            options: {
                XJZY: []
            },
            newFormSaved: true, //新增表单是否保存
            formIndex: 0,
            hasEditCol: false,
            checked: false, //是否存在审核
            rowColumnNumber: 18, //每行列数
            customTitle: [
                {
                    from: "student_admission_information_t",
                    value: "入学信息"
                }
            ],
            universList: [],
            getCodeList: [],
            searchColumns: [
                "FACULTY_",
                "STATUS_PROFESSION_",
                "CULTURE_PROFESSION_",
                "PROFESSION_",
                "CATEGORY_",
                "GRADUATE_SCHOOL_",
                "MAJOR_CODE_",
                "SCHOOL_UNIT_CODE_",
                "CATEGORY_CODE_",
                "NATION_",
                "COOPERATIVE_SCHOOL_",
                "UNION_COLLEGE_"
            ],
            dateRangeMap: null,
            citys: null,
            hasChecked: false,
            hasMajorDirectionName: false, //学籍信息，是否显示专业方向名称
            majorDirectionName: "MAJOR_DIRECTION_CODE_",
            toolOptions: {
                toolbar: {
                    zoomIn: 4,
                    zoomOut: 4,
                    oneToOne: 4,
                    reset: 0,
                    prev: 0,
                    next: 0,
                    rotateLeft: 4,
                    rotateRight: 4,
                    flipHorizontal: 4,
                    flipVertical: 4
                }
            },
            ralationField: [
                "MAJOR_DIRECTION_CODE_",
                "CULTURE_PROFESSION_",
                "DEGREE_TYPE_",
                "TRAINING_LEVEL_",
                "CULTURE_LEVEL_",
                "ORIGINAL_COLLEGE_COUNTRY_"
            ],
            trainingLevelRelation: [
                //培养层次改变，重新关联的字段
                "X_RXFS",
                "X_ZXJH",
                "X_XWLB",
                "G_ML",
                "G_XWDM",
                "education"
            ],
            degreeTypeRelation: [
                //学位类型改变，重新关联的字段
                "X_RXFS",
                "G_ML"
            ],
            profession: [
                "PROFESSION_",
                "STATUS_PROFESSION_",
                "CULTURE_PROFESSION_"
            ]
        };
    },
    components: {
        differenceDialog
    },
    mounted() {
        let dateRangeMap = new Map();
        dateRangeMap.set("END_TIME_", "START_TIME_");
        dateRangeMap.set("EFFECTIVE_END_TIME_", "EFFECTIVE_START_TIME_");
        dateRangeMap.set("END_DATE_", "START_DATE_");
        dateRangeMap.set("DURATION_STAY_", "DURATION_STAY_START_");
        dateRangeMap.set("PASSPORT_EXPIRE_", "PASSPORT_EFFECTIVE_");
        this.dateRangeMap = dateRangeMap;
        this.init();
    },
    methods: {
        init() {
            this.myForms = [];
            this.dynamicValidateForms = {};
            this.data = [];
            this.postData.stuDetailInfoList = [];
            this.newFormSaved = true;
            this.formIndex = 0;
            this.checked = false;

            this.options = {};

            let query = {
                studentId: this.uid,
                fieldClasses: Array.isArray(this.tableName)
                    ? this.tableName
                    : [this.tableName]
            };
            getStudentDetail(query).then(res => {
                let _this = this
                if (res.code == 200 && res.data) {
                    this.data = res.data;
                    if(this.data.length>1){
                      if (this.data[1].stuAttriInfos.length>28){
                        this.data[1].stuAttriInfos[28].type = 'input';
                      } ;
                    }
                    this.XY = this.data[0].stuAttriInfos[0].columnValue;    /*学院*/
                    //  if (this.data[0].stuAttriInfos.length > 11){
                    //    this.DQNJ = this.data[0].stuAttriInfos[11].columnValue;  /*当前年级*/
                    //  } ;
                     if(this.data[0].stuAttriInfos) {
                         for(let i = 0 ; i < this.data[0].stuAttriInfos.length; i++) {
                             if(this.data[0].stuAttriInfos[i].fieldId == 248) {
                                 this.XJXY = this.data[0].stuAttriInfos[i].columnValue
                             } // 学籍学院
                             if(this.data[0].stuAttriInfos[i].fieldId == 76) {
                                 this.DQNJ = this.data[0].stuAttriInfos[i].columnValue
                             } // 当前年级

                         }
                     }
                     // 预置学籍专业下拉数据
                     if(_this.DQNJ && _this.XJXY) {
                         let parm = {
                            grade: _this.DQNJ,
                            statusFacultyList: [_this.XJXY]
                        }
                        let xjzy = []
                        _this.$set(_this.options, 'XJZY', []);
                         findStatusProfessionList(parm).then(resT=> {
                            if(resT.code === 200) {
                                resT.data.forEach(val=> {
                                    xjzy.push(
                                        {
                                            label: val.professionName + '(' + val.professionCode + ')',
                                            value: val.statusProfessionCode
                                        }
                                    )
                                })
                                _this.$set(_this.options, 'XJZY', xjzy);
                            }
                        })
                     }
                    if( this.data[0].stuAttriInfos.length > 31 && this.data[0].stuAttriInfos[31].columnValue){
                      this.XWLX = this.data[0].stuAttriInfos[31].columnValue
                    }
                    this.formIndex = res.data.length;
                    for (const item of res.data) {
                        if (
                            !this.hasEditCol &&
                            item.stuAttriInfos.some(column => column.isEdit)
                        ) {
                            this.hasEditCol = true;
                        }
                        item.stuAttriInfos.forEach(column => {
                            if (column.type == "date" && column.columnValue) {
                                column.columnValue = moment(
                                    column.columnValue
                                ).format("YYYY-MM-DD");
                            }
                            if (column.columnValue == 'Y') {
                               column.columnValue = '1';
                            } else if(column.columnValue == 'N') {
                                column.columnValue = '0';
                            }
                            if (column.columnValue == 'MQ==') {
                               column.columnValue = '1';
                            } else if(column.columnValue == 'MA==') {
                                column.columnValue = '0';
                            }
                            if (
                                column.type == "select" &&
                                column.value &&
                                this.searchColumns.includes(column.column)
                            ) {
                                column.isSearch = true;
                            }
                            if (column.type == "year" && column.columnValue) {
                                column.columnValue = column.columnValue.toString();
                            }
                            if (column.inReview) {
                                this.hasChecked = true;
                            }
                            if (column.column === this.majorDirectionName) {
                                this.hasMajorDirectionName = true;
                                column.value = this.majorDirectionName;
                            }
                        });
                    }
                }
                this.convertForm();
                this.queryDic();
                this.initFiles();
                
                
            });
            
    },
        nationChange(code) {
            let _this = this
            // 获取登陆用户学院
            let mockUser = JSON.parse(localStorage.getItem('sessiondata')).mockUser
            let user = JSON.parse(localStorage.getItem('sessiondata')).user
            this.universList = []
            

            // this.getCodeList = []
        if (mockUser && mockUser.projId) {
            // 本科生
            if(mockUser.projId == '1') {

                this.getUniversities('bks', code)

            } else {
                this.getUniversities('yjs', code)
            }
        } else if (user && user.projId) {
            // 本科生
            if(mockUser.projId == '1') {
                // 本科生获取学院下拉框数据
                this.getUniversities('bks', code)
            } else {
                // 研究生获取学院下拉框数据
                this.getUniversities('yjs', code)
            }
        }

        },
        getUniversities(type,code) {
            if(type === 'bks') {
            universities({code: code}).then(res=> {
                if(res.code === 200) {
                    res.data.forEach(val=> {
                        this.universList.push(
                            {
                                label: val.universityNameZN,
                                value: val.universityCode
                            }
                        )
                    })
                }
            })
        } else if(type === 'yjs') {
            getCollegeListByNationCode({code: code, collegeId: ''}).then(res=> {
                if(res.code === 200) {
                    res.data.forEach(val=> {
                        this.universList.push(
                            {
                                label: val.collegeName,
                                value: val.collegeCode
                            }
                        )
                    })
                }
            })
        }

    },
        // 对方院校、院所 与所属国家联动
        getNation(code) {
            let _this = this
            if(_this.getCodeList) {
                _this.getCodeList.forEach(val=> {
                    if(val.label === code) {
                        if(_this.dynamicValidateForms && _this.dynamicValidateForms.dynamicValidateForm0 && _this.dynamicValidateForms.dynamicValidateForm0.columns) {
                        _this.dynamicValidateForms.dynamicValidateForm0.columns.forEach(col=> {
                                if(col.column === 'ORIGINAL_COLLEGE_COUNTRY_') {
                                col.columnValue = val.value
                               }
                            })
                        }
                    }
                })
            }
        },
        initFiles() {
            this.myForms.forEach(form => {
                let col = this.dynamicValidateForms[form.formName].columns.find(
                    c => c.column == "FILE_"
                );
                if (!col || !col.columnValue) return;
                form.files = [];
                this.loadImage(col.columnValue.split(";"), form);
            });
        },
        convertForm() {
            let forms = [];
            this.data.forEach((item, index) => {
                let formName = "dynamicValidateForm" + index;
                let columns = _.cloneDeep(item.stuAttriInfos);
                columns.forEach((c, index) => {
                    c.index = index;
                });
                this.$set(this.dynamicValidateForms, formName, {
                    id: item.id,
                    columns
                });
                forms.push({
                    formName: formName,
                    isEdit: false,
                    rows: this.calcRowColumnRelation(item),
                    title: this.getTitle(item),
                    files: [],
                    ralationOptions: null
                });
            });
            this.myForms = forms;
        },
        calcRowColumnRelation(item) {
            let rows = [];
            let columns = [];
            for (let i = 0; i < item.stuAttriInfos.length; i++) {
                columns.push(item.stuAttriInfos[i].fieldId);
                if ((i + 1) % this.rowColumnNumber == 0) {
                    rows.push({
                        columns: columns.slice(0, columns.length)
                    });
                    columns = [];
                }
            }
            if (columns.length > 0) {
                rows.push({ columns });
            }
            return rows;
        },
        getTitle(item) {
            let from = null;
            if (item.stuAttriInfos.length > 0) {
                from = item.stuAttriInfos[0].from;
            }
            let title = this.customTitle.find(t => t.from == from);
            return title ? title.value : null;
        },
        getRows(formData, colData) {
            return _.chunk(
                formData.filter(data => colData.includes(data.fieldId)),
                3
            );
        },
        getColumns(columns, rowColumns) {
            return columns.filter(col => rowColumns.includes(col.fieldId));
        },
        gradeChange(val){
            this.DQNJ = val;
            this.queryDic();
            // 与学籍专业关联
            if(this.dynamicValidateForms && this.dynamicValidateForms.dynamicValidateForm0 && this.dynamicValidateForms.dynamicValidateForm0.columns) {
                for(let i = 0; i < this.dynamicValidateForms.dynamicValidateForm0.columns.length; i++) {
                    if(this.dynamicValidateForms.dynamicValidateForm0.columns[i].fieldId == 68) {
                        this.dynamicValidateForms.dynamicValidateForm0.columns[i].columnValue = null
                        // 年级，学籍学院改变后  清空学籍专业
                    }
                }
            }
            let parm = {
                grade: this.DQNJ,
                statusFacultyList: [this.XY]
            }
            this.$set(this.options, 'XJZY', []);
            let xjxy = []
            if(parm.grade && parm.statusFacultyList) {
                findStatusProfessionList(parm).then(resT=> {
                    if(resT.code === 200) {
                        resT.data.forEach(val=> {
                            xjxy.push(
                                {
                                    label: val.professionName + '(' + val.professionCode + ')',
                                    value: val.statusProfessionCode
                                }
                            )
                        })
                        this.$set(this.options, 'XJZY', xjxy);
                    }
                })
            }
        },
        queryDic() {
            let keys = [];
            this.data.forEach(item => {
                item.stuAttriInfos.forEach(column => {
                    if (
                        column.type == "select" &&
                        column.value &&
                        !keys.includes(column.value)
                    ) {
                        keys.push(column.value);
                    }
                });
            });
            if (!this.XY){
              this.XY = '';
            } ;
            if( this.DQNJ && this.DQNJ.length > 4){
              this.DQNJ = '';
            }
            const data = {
                lang: this.$store.getters.language || "cn",
                type: "allChild",
                keys: keys,
                filter: {
                  facultys: [this.XY],
                  grade: this.DQNJ,
                  degreeType: [this.XWLX]
                }
            };
            let _this = this;
            queryDic(data).then(res => {
              let cot = 0 ;
                if (res.code === 200) {
                    let _that = this;
                    let keyword = "其他";
                    let _fill = function(type, data) {
                        let items = [];
                        for (const key in data[type]) {
                            items.push({
                                value: key,
                                label: data[type][key]
                            });
                            if (type === 'G_ZY'){
                              if (_this.data[0].stuAttriInfos[4].columnValue === data[type][key]){
                                ++cot;
                                /*debugger;*/
                              } ;
                            } ;
                        }
                        if (cot === 0 && _this.tableName !== 'student_joint_training_t'){
                          if (_this.dynamicValidateForms.dynamicValidateForm0.columns.length>4){
                            _this.dynamicValidateForms.dynamicValidateForm0.columns[4].columnValue = null;
                           
                          } else if (_this.dynamicValidateForms.dynamicValidateForm0.columns.length>5) {
                               _this.dynamicValidateForms.dynamicValidateForm0.columns[5].columnValue = null;
                          }
                          /*_this.options[_this.majorDirectionName] = [];*/
                        } else {
                          if (_this.dynamicValidateForms.dynamicValidateForm0.columns.length > 4){
                            _this.hasMajorDirectionName = true;
                            _this.dynamicValidateForms.dynamicValidateForm0.columns[4].columnValue = _this.data[0].stuAttriInfos[4].columnValue;
                            
                            /* _this.getMajorDirectionName();*/
                          } else if(_this.dynamicValidateForms.dynamicValidateForm0.columns.length > 5) {
                              _this.dynamicValidateForms.dynamicValidateForm0.columns[5].columnValue = _this.data[0].stuAttriInfos[5].columnValue;
                          }
                        };
                        items = _.sortBy(items, ["value"]);
                        items = items
                            .filter(o => o.label.indexOf(keyword) == -1)
                            .concat(
                                items.filter(
                                    o => o.label.indexOf(keyword) != -1
                                )
                            );
                        _that.options[type] = items;
                    };
                    keys.forEach(key => {
                        this.$set(this.options, key, []);
                        _fill(key, res.data);
                    });
                    this.citys = getCitys(this.options);
                    if(cot === 0) this.hasMajorDirectionName = null;
                    if (this.hasMajorDirectionName) {
                        this.getMajorDirectionName();
                    }

                }
            });
        },
        editForm(form) {
            this.nationChange('')
            form.isEdit = form.isEdit ? false : true;
            form.columns = _.cloneDeep(
                this.dynamicValidateForms[form.formName].columns
            );

            let result = this.getRalationOptions(form);
            if (result) {
                result.then(r => {
                    form.ralationOptions = r; //设置表单关联字典
                });
            }
        },
        cancel(form) {
            form.ralationOptions = null; //设置表单关联字典为null
            if (this.dynamicValidateForms[form.formName].id == ADD_FORM) {
                this.dynamicValidateForms[
                    form.formName
                ].id = this.getRandomId();
                this.newFormSaved = true;
            }

            let changed = false;
            this.dynamicValidateForms[form.formName].columns.forEach(
                oldColumn => {
                    let newColumn = form.columns.find(
                        c =>
                            c.column == oldColumn.column &&
                            c.fieldId == oldColumn.fieldId
                    );
                    if (
                        newColumn &&
                        newColumn.columnValue != oldColumn.columnValue
                    ) {
                        changed = true;
                    }
                }
            );
            if (changed) {
                this.prompt(() => {
                    this.revertFiles(form);
                    this.dynamicValidateForms[form.formName].columns =
                        form.columns;
                    form.columns = null;
                    form.isEdit = false;
                });
            } else {
                form.columns = null;
                form.isEdit = false;
            }


            if (this.tempVal != ''){
              queryZYFX(this.tempVal).then(res => {

                let key = 'X_FX';
                let opts = Object.keys(res.data[key]).map(i => ({
                  value: i,
                  label: res.data[key][i]
                }));
                /*debugger;*/
                if (opts.length != 0) {
                  this.options[this.majorDirectionName] = opts;
                } else {
                  this.options[this.majorDirectionName] = [];
                }
              });
            } ;
            this.$refs[form.formName][0].clearValidate();
        },
        deleteForm(form) {
            this.$confirm("是否刪除该行?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(() => {
                let id = this.dynamicValidateForms[form.formName].id;
                if (Number.isInteger(id)) {
                    let stuDetail = this.postData.stuDetailInfoList.find(
                        stuDetail => stuDetail.id == id
                    );
                    let rawDetail = this.data.find(c => c.id == id);
                    if (stuDetail) {
                        stuDetail.stuAttriInfos = _.cloneDeep(
                            rawDetail.stuAttriInfos
                        );
                        stuDetail.stuAttriInfos.forEach(col => {
                            col.oldColumnValue = col.columnValue;
                            col.columnValue = null;
                        });
                        stuDetail.operType = FORM_TYPE.DELETE;
                    } else {
                        let stuAttriInfos = _.cloneDeep(
                            rawDetail.stuAttriInfos
                        );
                        stuAttriInfos.forEach(col => {
                            col.oldColumnValue = col.columnValue;
                            col.columnValue = null;
                        });
                        this.postData.stuDetailInfoList.push({
                            stuAttriInfos: stuAttriInfos,
                            id: id,
                            operType: FORM_TYPE.DELETE
                        });
                    }
                } else {
                    _.remove(
                        this.postData.stuDetailInfoList,
                        item => item.id == id
                    ); //删除TEMP表单
                }
                _.remove(this.myForms, item => item.formName == form.formName);
                this.$set(this.dynamicValidateForms, form.formName, null);
            });
        },
        checkAndSubmit() {
            if (this.myForms.some(form => form.isEdit)) {
                this.$message("请先确定或取消编辑");
                return;
            }
            if (this.postData.stuDetailInfoList.length == 0) {
                this.$message("内容未修改，无需提交");
                return;
            }
            this.$confirm("您确定要提交吗?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            })
                .then(() => {
                    let checked = false;
                    for (const item of this.postData.stuDetailInfoList) {
                        if (
                            item.stuAttriInfos &&
                            item.stuAttriInfos.some(
                                field =>
                                    field.isSchoolCheck || field.isCollegeCheck
                            )
                        ) {
                            checked = true;
                            break;
                        }
                    }
                    let fn = () => {
                        this.checked = checked;
                        this.$refs.diffDialog.open();
                    };
                    if (checked) {
                        fn();
                    } else {
                        this.noCheckSubmit(() => {
                            fn();
                        });
                    }
                })
                .catch(() => {});
        },
        //无审核提交
        noCheckSubmit(callback) {
            stuDetailSubmit(this.handleSelectColumn()).then(res => {
                if (res.code == 200 && callback) {
                    callback();
                }
            });
        },
      changexx(form,val) {
          let _this = this
          if(val.value == 'X_YX' && val.fieldId == 248) {
            // 与学籍专业关联
            if(this.dynamicValidateForms && this.dynamicValidateForms.dynamicValidateForm0 && this.dynamicValidateForms.dynamicValidateForm0.columns) {
                for(let i = 0; i < this.dynamicValidateForms.dynamicValidateForm0.columns.length; i++) {
                    if(this.dynamicValidateForms.dynamicValidateForm0.columns[i].fieldId == 68) {
                        this.dynamicValidateForms.dynamicValidateForm0.columns[i].columnValue = null
                        // 年级，学籍学院改变后  清空学籍专业
                    }
                    if(this.dynamicValidateForms.dynamicValidateForm0.columns[i].fieldId == 76) {
                        this.DQNJ = this.dynamicValidateForms.dynamicValidateForm0.columns[i].columnValue  
                        // 赋值当前年级
                    }
                }
                 
            }
             this.XY = val.columnValue;
             let parm = {
                grade: this.DQNJ,
                statusFacultyList: [this.XY]
            }
            //  this.queryDic();
            this.$set(this.options, 'XJZY', []);
             let xjxy = []
             if(parm.grade && parm.statusFacultyList) {      
                findStatusProfessionList(parm).then(resT=> {
                    if(resT.code === 200) {
                        resT.data.forEach(val=> {
                            xjxy.push(
                                {
                                    label: val.professionName + '(' + val.professionCode + ')',
                                    value: val.statusProfessionCode
                                }
                            )
                        })
                        this.$set(this.options, 'XJZY', xjxy);
                    }
                })
             }
          } else if(val.value == 'X_YX' && val.fieldId != 248) {
              this.XY = val.columnValue;
              this.queryDic();
          } else if (val.value == 'G_ZY' && val.columnValue != '') {
              this.tempVal = val.columnValue;
                queryZYFX(val.columnValue).then(res => {

                    let key = 'X_FX';
                    let opts = Object.keys(res.data[key]).map(i => ({
                      value: i,
                      label: res.data[key][i]
                    }));
                    /*debugger;*/

                    if (opts.length != 0) {
                      this.options[this.majorDirectionName] = opts;
                    } else {
                      this.options[this.majorDirectionName] = [];
                    //   console.log(this.dynamicValidateForms);
                      /*this.tempVal = this.dynamicValidateForms.dynamicValidateForm0.columns[5].columnValue*/
                      this.dynamicValidateForms.dynamicValidateForm0.columns[5].columnValue = null
                    }
                    ;

                  }
                ).catch(err => {
                  this.options[this.majorDirectionName] = [];
                  this.dynamicValidateForms.dynamicValidateForm0.columns[5].columnValue = null
                });
            } else if(val.value === "G_GJQU") {
                
                if(_this.dynamicValidateForms && _this.dynamicValidateForms.dynamicValidateForm0 && _this.dynamicValidateForms.dynamicValidateForm0.columns) {
                _this.dynamicValidateForms.dynamicValidateForm0.columns.forEach(col=> {
                        if(col.column === 'UNION_COLLEGE_') {
                        col.columnValue = ''
                        }
                    })
                }
                _this.nationChange(val.columnValue)
            }
          },
        //有审核提交
        hasCheckSubmit(fileList, modifyDesc) {
            submitField(
                this.uid,
                fileList,
                modifyDesc,
                this.handleSelectColumn(),
                this.data,
                () => {
                    this.$refs.diffDialog.close();
                    this.$message({
                        type: "success",
                        message: this.$t("message.saveSuccess")
                    });
                    setTimeout(() => {
                        this.init();
                    }, 500);
                }
            );
        },
        handleSelectColumn() {
            let _this = this
            let postData = _.cloneDeep(this.postData);
            postData.stuDetailInfoList.forEach(s => {
                if (s.operType == FORM_TYPE.ADD) {
                    s.id = null;
                }
                s.stuAttriInfos.forEach(col => {
                    if (col.isEdit && col.type == "select" && col.value) {
                        let newOpt = this.options[col.value].find(
                            option => option.value == col.columnValue
                        );
                        let oldOpt = this.options[col.value].find(
                            option => option.value == col.oldColumnValue
                        );
                        if (newOpt) {
                            col.newRealValue = newOpt.label;
                        }
                        if (oldOpt) {
                            col.oldRealValue = oldOpt.label;
                        }
                    } else if(col.fieldId == 68) {
                        _this.options.XJZY.forEach(val=> {
                            if(val.value == col.columnValue) {
                                col.newRealValue = val.label;
                            }
                        })
                    }
                });
            });
            return postData;
        },
        //保存到本地
        save(form) {
            this.$refs[form.formName][0].validate(valid => {
                if (valid) {
                    form.isEdit = false;
                    let columns = null;
                    let type = null;
                    let dynamicForm = this.dynamicValidateForms[form.formName]; //当前操作的表单

                    if(dynamicForm.columns.length > 28 && /[$￥]+/gi.test(dynamicForm.columns[28].columnValue)){
                      /*this.$message({
                        message: "不能存在$(￥)符",
                        type: "warning"
                      });*/
                      dynamicForm.columns[28].columnValue = dynamicForm.columns[28].columnValue.replace(/[&\|\\\*^%$￥#@\-]/g,"");
                      return false;
                    }
                    if (dynamicForm.id == ADD_FORM) {
                        this.newFormSaved = true;
                        dynamicForm.id = this.getRandomId();
                        columns = dynamicForm.columns.filter(
                            c => c.isEdit && c.columnValue != null
                        );
                        type = FORM_TYPE.ADD;
                    } else if (Number.isInteger(dynamicForm.id)) {
                        columns = this.getDiffColumnData(form.formName);
                        type = FORM_TYPE.EDIT;
                    } else {
                        columns = dynamicForm.columns.filter(
                            c => c.isEdit && c.columnValue != null
                        );
                        type = FORM_TYPE.ADD;
                    }
                    let from = dynamicForm.columns[0].from;
                    if (columns.length == 0) {
                        _.remove(this.postData.stuDetailInfoList, item => {
                            return (
                                item.id == dynamicForm.id &&
                                item.stuAttriInfos[0].from == from
                            );
                        });
                    } else {
                        let item = this.postData.stuDetailInfoList.find(
                            item =>
                                item.id == dynamicForm.id &&
                                item.stuAttriInfos[0].from == from
                        );
                        if (item) {
                            item.stuAttriInfos = columns;
                        } else {
                            this.postData.stuDetailInfoList.push({
                                stuAttriInfos: columns,
                                id: dynamicForm.id,
                                operType: type
                            });
                        }
                    }
                } else {
                    return false;
                }
            });
        },
        //获取差异列数据
        getDiffColumnData(formName) {
            let columns = [];
            let from = this.dynamicValidateForms[formName].columns[0].from;
            //多张表可能存在id相同，不能只用id关联，需要使用表名+id
            let row = this.data.find(
                row =>
                    row.id == this.dynamicValidateForms[formName].id &&
                    row.stuAttriInfos[0].from === from
            );
            this.dynamicValidateForms[formName].columns
                .filter(newColumn => newColumn.isEdit)
                .forEach(newColumn => {
                    row.stuAttriInfos
                        .filter(oldColumn => oldColumn.isEdit)
                        .forEach(oldColumn => {
                            if (
                                newColumn.column == oldColumn.column &&
                                newColumn.columnValue != oldColumn.columnValue
                            ) {
                                newColumn.oldColumnValue =
                                    oldColumn.columnValue;
                                columns.push(newColumn);
                            }
                        });
                });
            return columns;
        },
        //新增表单
        addForm() {
            if (this.data.length == 0) {
                return;
            }
            if (!this.newFormSaved) {
                this.$message({
                    message: "请先保存前一个新增的数据",
                    type: "warning"
                });
                return;
            }
            let newForm = "dynamicValidateForm" + this.formIndex++;
            let newColumns = _.cloneDeep(this.data[0].stuAttriInfos);
            newColumns.forEach((column, index) => {
                column.columnValue = null;
                column.index = index;
            });
            this.$set(this.dynamicValidateForms, newForm, {
                columns: newColumns,
                id: ADD_FORM
            });
            this.myForms.push({
                formName: newForm,
                isEdit: true,
                rows: this.calcRowColumnRelation(this.data[0]),
                title: null,
                files: [],
                columns: _.cloneDeep(newColumns),
                ralationOptions: null
            });
            this.newFormSaved = false;
        },
        toDateByLong(t) {
            return t ? moment(t).format("YYYY-MM-DD") : null;
        },
        //根据column字段获取Option对应文本
        getOptionText(column) {
            if (
                column.value != null &&
                this.options.hasOwnProperty(column.value)
            ) {
                let option = this.options[column.value].find(
                    c => c.value == column.columnValue
                );
                if (option) {
                    return option.label;
                } else {
                    // 如果没有匹配项 取columnValue
                    return column.columnValue;
                }
                //专业的数据不同，研究生columnValue为code，本科生columnValue为文本，显示存在问题
                //解决方法：若option未找到匹配项，直接显示columnValue
                if (this.profession.includes(column.column)) {
                    return column.columnValue;
                }
            } else if(column.fieldId == '166') {
                if(column.columnValue && this.universList) {
                    for(let i = 0; i < this.universList.length; i++) {
                    if(this.universList[i].value == column.columnValue) {
                        return this.universList[i].label;
                        }
                    }
                }
            } else if(column.fieldId == '68' && column.columnValue) {
                // 学籍专业数据显示
                if(column.columnValue && column.oldColumnValue) {
                    for(let i = 0; i < this.options.XJZY.length; i++) {
                    if(this.options.XJZY[i].value == column.columnValue) {
                        return this.options.XJZY[i].label.substring(0,this.options.XJZY[i].label.length-8);
                        }
                    }
                } else if(column.columnValue) {
                    return column.columnValue;
                }
            }
            // else {
            //     return null;
            // } 
        },
        getRandomId() {
            return "TEMP" + Math.floor(Math.random() * 100000);
        },
        prompt(fn) {
            this.$confirm(
                "返回后您的当前操作将不会保存，请确定操作",
                this.$t("message.prompt"),
                {
                    confirmButtonText: this.$t("message.confirm"),
                    cancelButtonText: this.$t("message.cancel"),
                    type: "warning"
                }
            )
                .then(() => {
                    fn();
                })
                .catch(() => {});
        },
        //检查是否存在改变
        checkModify() {
            if (this.myForms.some(form => form.isEdit)) {
                this.$message("请先确定或取消编辑");
                return null;
            }
            return this.postData.stuDetailInfoList.length > 0;
        },
        getAllRules(column, formName) {
            let relationMap = new Map();
            relationMap.set("NUMBER_", "TYPE_");
            let typeColumn = this.dynamicValidateForms[formName].columns.find(
                c => c.column === relationMap.get(column.column)
            );
            let dateEndColumn = this.dateRangeMap.has(column.column)
                ? this.dynamicValidateForms[formName].columns.find(
                      c => c.column === this.dateRangeMap.get(column.column)
                  )
                : null;
            return getRules(
                column,
                relationMap,
                typeColumn,
                this.dateRangeMap,
                dateEndColumn
            );
        },
        handleError(err, file, fileList) {
            this.$message({
                type: "error",
                message: err
            });
        },
        handleExceed(files, fileList) {
            this.$message({
                type: "error",
                message: "照片超出个数限制"
            });
        },
        handleSuccess(res, file, fileList, form) {
            let columns = this.dynamicValidateForms[form.formName].columns;
            let col = columns.find(c => c.column == "FILE_");
            if (!col) return;
            if (col.columnValue) {
                col.columnValue += ";" + res.data[file.name].objectkey;
            } else {
                col.columnValue = res.data[file.name].objectkey;
            }
            getImageData(res.data[file.name].objectkey).then(res => {
                if (res.code == 200 && res.data) {
                    form.files.push({
                        url: res.data.base,
                        objectKey: res.data.objectkey,
                        uid: file.uid
                    });
                }
            });
        },
        handleRemove(file, fileList, form) {
            let columns = this.dynamicValidateForms[form.formName].columns;
            let col = columns.find(c => c.column == "FILE_");
            if (!col) return;
            let val = col.columnValue
                .replace(";" + file.objectKey, "")
                .replace(file.objectKey + ";", "")
                .replace(file.objectKey, "");
            col.columnValue = val;
            form.files = form.files.filter(f => f.objectKey != file.objectKey);
        },
        beforeAvatarUpload(file) {
            const isJPG = file.type === "image/jpeg";
            const isPNG = file.type === "image/png";
            const isLt2M = file.size / 1024 / 1024 < 2;
            let correct = false;
            if (isJPG == false && isPNG == false) {
                this.$message.error("证书照片只能是JPG或PNG格式!");
            } else {
                correct = true;
            }
            if (!isLt2M) {
                this.$message.error("证书照片大小不能超过 2MB!");
            }
            return correct && isLt2M;
        },
        getImg(file, form) {
            let obj = form.files.find(f => f.objectKey == file);
            return obj ? obj.url : null;
        },
        //还原附件
        revertFiles(form) {
            let fileColumn = form.columns.find(
                c => c.column == "FILE_" && c.isEdit
            );
            if (fileColumn) {
                let val = fileColumn.columnValue;
                let val2 = this.dynamicValidateForms[
                    form.formName
                ].columns.find(c => c.column == "FILE_" && c.isEdit)
                    .columnValue;
                if (!val) {
                    form.files = [];
                } else if (val != val2) {
                    form.files = [];
                    this.loadImage(val.split(";"), form);
                }
            }
        },
        loadImage(files, form) {
            files.forEach(file => {
                if (file) {
                    getImageData(file).then(res => {
                        if (res.code == 200 && res.data) {
                            form.files.push({
                                url: res.data.base,
                                objectKey: res.data.objectkey
                            });
                        }
                    });
                }
            });
        },
        handleRalationField(form, c) {
          if ( c.column === 'CULTURE_PROFESSION_'){
            this.changexx(form,c);
          }else {
            /*培养层次*/
            /*debugger*/
            let relations =
              c.column == "DEGREE_TYPE_"
                ? this.degreeTypeRelation
                : this.trainingLevelRelation;
            //根据业务需求，本科生或博士生，在学位类型改变时其入学方式不变
            let changed = true;
            if (c.column == "DEGREE_TYPE_") {
              changed = !this.dynamicValidateForms[
                form.formName
                ].columns.some(
                col =>
                  col.column === "TRAINING_LEVEL_" &&
                  ["1", "6"].includes(col.columnValue)
              );
            }
            this.dynamicValidateForms[form.formName].columns.forEach(col => {
              if (col.type == "select" && relations.includes(col.value)) {
                if (!changed && col.value === "X_RXFS") {
                  return;
                }
                col.columnValue = null;
              }
            });
            let result = this.getRalationOptions(form);
            if (result) {
              result.then(r => {
                form.ralationOptions = r; //设置表单关联字典
              });
            }
          }
        },
        //获取关联字典
        getRalationOptions(form) {
            let data = {};
            let hasRelation = false;
            this.dynamicValidateForms[form.formName].columns
                .filter(c => this.ralationField.includes(c.column))
                .forEach(c => {
                    if (c.column == "DEGREE_TYPE_") {
                        data.degreeTypeCode = c.columnValue;
                        hasRelation = true;
                    } else if (c.column == "TRAINING_LEVEL_") {
                        data.trainingLevelCode = c.columnValue;
                        hasRelation = true;
                    } else if (c.column == "CULTURE_LEVEL_") {
                        data.culTureLevelCode = c.columnValue;
                        hasRelation = true;
                    }
                });
            //当前表单无关联字典，返回null
            if (!hasRelation) {
                return null;
            }
            //重新获取关联字典
            return findStuDicLinkage(data).then(res => {
                if (res.code == 200) {
                    let options = {};
                    for (let key in res.data) {
                        let option = [];
                        for (let label in res.data[key]) {
                            option.push({
                                label: label,
                                value: res.data[key][label]
                            });
                        }
                        options[key] = option;
                    }
                    return options;
                }
            });
        },
        getOptions: function(form, value) {
            //表单无关联字典
            if (!form.ralationOptions) {
                return this.options[value];
            }
            //表单有关联字典，但不是关联字典
            if (!this.trainingLevelRelation.includes(value)) {
                return this.options[value];
            }
            return form.ralationOptions.hasOwnProperty(value)
                ? form.ralationOptions[value]
                : [];
        },



        //获取专业方向名称
        getMajorDirectionName() {
            getDirections(this.uid).then(res => {
                if (res.code == 200 && res.data) {
                    let directions = [];
                    for (let key in res.data) {
                        directions.push({
                            label: res.data[key],
                            value: key
                        });
                    }
                    this.options[this.majorDirectionName] = directions;

                }else{
                  let val = this.data[0].stuAttriInfos[5].columnValue.substring(0,this.data[0].stuAttriInfos[5].columnValue.indexOf('_'));
                  queryZYFX(val).then(res => {

                    let key = 'X_FX';
                    let opts = Object.keys(res.data[key]).map(i => ({
                      value: i,
                      label: res.data[key][i]
                    }));
                    /*debugger;*/
                    if (opts.length != 0) {
                      this.options[this.majorDirectionName] = opts;
                    } else {
                      this.options[this.majorDirectionName] = [];
                    }
                  });
                }
            });
        }
    }
};
</script>
<style lang="scss" scoped>
.top {
    height: 32px;
    .title {
        float: left;
        line-height: 32px;
        font-size: 16px;
    }
    .change-tip {
        line-height: 32px;
        font-size: 16px;
        float: left;
        margin-left: 15px;
        .color-block {
            background: #ff7800;
            display: inline-block;
            width: 25px;
            height: 12px;
            margin: 0 5px 0 0;
        }
    }
}
.form-title {
    margin-bottom: 10px;
    font-size: 16px;
}
.info {
    overflow: auto;
    margin-bottom: 24px;
    border: 1px solid #ced6df;
    background: #f3f6f8;
    padding: 24px;
    padding-top: 0;
    font-size: 14px;
    .edit-icon {
        height: 21px;
        width: 100%;
        margin-top: 10px;
        font-size: 20px;
        text-align: right;
        i {
            cursor: pointer;
        }
    }
    .is-require {
        color: #f56c6c;
    }
}
.add-btn {
    margin-top: 24px;
    border: 1px solid #ced6df;
    line-height: 40px;
    text-align: center;
    cursor: pointer;
}
.ie-hack {
    *line-height: 33px;
    *height: 33px;
}
.file-image {
    cursor: pointer;
    margin-right: 10px;
    border: 1px solid #c0ccda;
    border-radius: 6px;
}
.file-upload {
    & ::v-deep .el-upload-list__item {
        width: 220px;
    }
}
.field-checked {
    color: #ff7800;
}

.el-date-editor.el-input,
.el-date-editor.el-input__inner {
    width: 100%;
}
</style>
